<template>
  <el-card class="app-container">
    <div>
      <div class="itemTitle">排班管理</div>
      <div class="search">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-col :span="5">
            <el-form-item label="年份" prop="year">
              <el-date-picker
                clearable
                @change="handleQuery"
                value-format="yyyy"
                v-model="queryParams.year"
                :default-value="queryParams.year"
                type="year"
                placeholder="选择开始日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="月份" prop="month">
              <!-- <el-date-picker
                clearable
                @change="handleQuery"
                value-format="MM"
                v-model="queryParams.month"
                :default-value="queryParams.month"
                type="month"
                placeholder="选择结束日期"
              >
              </el-date-picker> -->
              <el-select
                @change="handleQuery"
                v-model="queryParams.month"
                placeholder="选择结束日期"
              >
                <el-option
                  v-for="dict in monthList"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>

            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['base:scheduling:add']"
            >新增</el-button
          >
          <!-- <el-button type="primary" @click="handleAddByDialog" v-hasPermi="['base:scheduling:add']">弹窗新增</el-button>
          <el-button type="success" @click="handleImport" v-hasPermi="['base:scheduling:import']">批量导入</el-button>
          <el-button type="warning"  @click="handleExport" v-hasPermi="['base:scheduling:export']">批量导出</el-button>
          <el-button type="warning"  @click="importTemplate" v-hasPermi="['base:scheduling:downImportTemplate']">下载导入模板</el-button> -->
        </div>
        <div class="ct-table">
          <!-- 设置 range 属性指定日历的显示范围。开始时间必须是周起始日，结束时间必须是周结束日，且时间跨度不能超过两个月。 -->
          <el-calendar v-model="activeMounth" :range="range">
            <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
            <template slot="dateCell" slot-scope="{ date, data }">
              <div class="riliBox">
                <span>{{ data.day.split("-").slice(1).join("-") }}</span>
                <el-popover placement="right" width="280" trigger="hover">
                  <div
                    class="item item1"
                    style="background-color: #f0f0f0;padding:4px 10px;border-radius: 2px;cursor: pointer;margin-bottom:4px;"
                    v-for="(item, index) in showHtml(data.day)"
                    :key="index"
                    @click="handleUpdate(item,2)"
                  >
                  <span> {{ showClasses(item.classes) }}</span>
                    <div>
                      <span>{{ item.userName }}&nbsp;</span>
                      <span>{{ item.workshopName }}&nbsp;</span>
                      <span>{{ item.phone }}</span>
                    </div>
                  </div>


                  <div
                    slot="reference"
                    class="item"
                    v-for="(item, index) in showHtml(data.day)"
                    :key="index"
                    :style="{'padding':index == 0?'4px 10px':'0px'}"
                    @click="handleUpdate(item,2)"
                  >
                    <div v-if="index == 0">
                      <span> {{ showClasses(item.classes) }}</span>
                      <div class="two">
                        <span>{{ item.userName }}&nbsp;</span>
                        <span>{{ item.workshopName }}&nbsp;</span>
                        <span>{{ item.phone }}</span>
                      </div>
                    </div>
                  </div>
                  <!-- <el-button slot="reference">click</el-button> -->
                </el-popover>
              </div>
            </template>
          </el-calendar>
          <!-- <elTables
              :table-data="tableData"
              :columns="tableColumns"
              :totalLength="total"
              :handle-current-change="handleCurrentChange"
              isPagin
              :curHeight="tableHeight"
          /> -->
        </div>
      </div>
    </div>
    <!-- 添加或修改排班管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      @close="cancel"
      class="dialog-form"
    >
      <!-- <p class="title-level2">二级标题可选</p> -->
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-col :span="12">
          <el-form-item label="值班开始日期" prop="startDate">
            <el-date-picker
              clearable
              :readonly="!isEdit"
              :disabled="!isEdit"
              v-model="form.startDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择值班开始日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="值班截止日期" prop="endDate">
            <el-date-picker
              clearable
              :readonly="!isEdit"
              :disabled="!isEdit"
              v-model="form.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择值班截止日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="值班人员" prop="userId">
            <deptAndDuty
              type-show="duty"
              @dutyChange="dutyChange"
              :dutyId="form.userId"
              :disabled="!isEdit"
            ></deptAndDuty>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="车间" prop="workshop">
            <el-select
              :readonly="!isEdit"
              :disabled="!isEdit"
              filterable
              v-model="form.workshop"
              placeholder="请选择车间"
              clearable
            >
              <el-option
                v-for="(dict, index) in listShop"
                :key="index"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="班次" prop="classes">
            <el-select
              v-model="form.classes"
              placeholder="请选择班次"
              :readonly="!isEdit"
              :disabled="!isEdit"
            >
              <el-option
                v-for="dict in classesList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer" s>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="800px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
  year: new Date().getFullYear() + "", //因为Element 的日期组件的数据类型不能为Number
  month: new Date().getMonth() + 1 + "",
};
import { getToken } from "@/utils/auth";
import {
  listSchedulingCalendar,
  pageScheduling,
  listScheduling,
  getScheduling,
  delScheduling,
  addScheduling,
  updateScheduling,
  exportScheduling,
  downImportTemplate,
} from "@/api/base/scheduling";
import { listShop } from "@/api/video/monitor";

export default {
  name: "Scheduling",
  computed:{
    showClasses (){
      return (classes)=>{
        return this.selectDictLabel(this.classesList, classes)
      }
    },
    // 返回日期内容
    showHtml() {
      return(val)=>{
        if (this.rqiList.indexOf(val) != -1) {
          return this.rqiNeirong[val];
        }
      }
    },
  },
  data() {
    return {
      monthList:[
        {
          dictValue:'1',
          dictLabel:'1月'
        },
        {
          dictValue:'2',
          dictLabel:'2月'
        },
        {
          dictValue:'3',
          dictLabel:'3月'
        },
        {
          dictValue:'4',
          dictLabel:'4月'
        },
        {
          dictValue:'5',
          dictLabel:'5月'
        },
        {
          dictValue:'6',
          dictLabel:'6月'
        },
        {
          dictValue:'7',
          dictLabel:'7月'
        },
        {
          dictValue:'8',
          dictLabel:'8月'
        },
        {
          dictValue:'9',
          dictLabel:'9月'
        },
        {
          dictValue:'10',
          dictLabel:'10月'
        },
        {
          dictValue:'11',
          dictLabel:'11月'
        },
        {
          dictValue:'12',
          dictLabel:'12月'
        }
      ],
      range: ["2019-03-04", "2019-03-24"],
      activeMounth: new Date(),
      tableHeight: 0,
      isEdit: false,
      dialogFormVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/base/scheduling/importData",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,
        startDate: null,
        phone: null,
        endDate: null,
        workshop: null,
        factoryId: null,
      },
      // 表单参数
      form: {},
      classesList: [],
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "值班人员不能为空", trigger: "change" },
        ],
        startDate: [
          {
            required: true,
            message: "值班开始日期不能为空",
            trigger: "change",
          },
        ],
        endDate: [
          {
            required: true,
            message: "值班截止日期不能为空",
            trigger: "change",
          },
        ],
        workshop: [
          { required: true, message: "车间不能为空", trigger: "change" },
        ],
        classes: [
          { required: true, message: "班次不能为空", trigger: "change" },
        ],
      },
      tableColumns: [
        { key: "userName", title: "值班人员" },
        { key: "startDate", title: "开始日期" },
        { key: "classes", title: "班次" },
        { key: "phone", title: "电话号码" },
        { key: "endDate", title: "结束日期" },
        { key: "workshop", title: "车间" },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:scheduling:edit"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 1);
                    },
                  },
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:scheduling:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 2);
                    },
                  },
                },
                "查看"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:scheduling:remove"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      listShop: [],
      rqiList: [],
      rqiNeirong: {},
    };
  },
  created() {
    this.getPage();
    this.getlistShop();
    // 获取报告类型等级字典数据
    this.getDicts("schedule_class").then((response) => {
      this.classesList = response.data;
    });

        // 获取报告类型等级字典数据
    this.getDicts("schedule_class").then((response) => {
      this.classesList = response.data;
    });

    
  },
  mounted() {
    this.$nextTick(() => {
      this.getTableHeight();
    });
  },
  methods: {
    //获取车间
    getlistShop() {
      listShop().then((res) => {
        this.listShop = res.data;
      });
    },
    // 组件传回的人员id
    dutyChange(val) {
      this.form.userId = val;
    },
    /** 下载模板操作 */
    importTemplate() {
      downImportTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    handleAddByDialog() {
      this.dialogFormVisible = true;
    },
    getTableHeight() {
      let height = document.getElementsByClassName("ct-table")[0].clientHeight;
      this.tableHeight = height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询排班管理列表 */
    getPage() {
      this.rqiList =[]
      this.rqiNeirong =[]
      this.loading = true;
      listSchedulingCalendar(this.queryParams).then((response) => {
        this.tableData = response.data;
        //设置返回
        this.range = [
          response.data[0].date,
          response.data[response.data.length - 1].date,
        ];
        for (let index = 0; index < this.tableData.length; index++) {
          const element = this.tableData[index];
          // 转换数据
          this.rqiList.push(element.date); //['2023-10-01'] 日期数组
          this.rqiNeirong[element.date] = element.schedulings; //日期对应的内容
          console.log(this.rqiList,"this.rqiList",this.rqiNeirong,"this.rqiNeirong");
        }
        // this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        userName: null,
        startDate: null,
        classes: null,
        phone: null,
        endDate: null,
        workshop: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit= true;
      this.title = "新增排班管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      if (type == 1) {
        this.isEdit = true;
      } else {
        this.isEdit = false;
      }
      this.reset();
      const id = row.id || this.ids;
      getScheduling(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isEdit= true;
        this.title = "编辑排班管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateScheduling(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getPage();
            });
          } else {
            addScheduling(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          let data;
          if (Array.isArray(ids)) {
            data = ids;
          } else {
            data = [ids];
          }
          return delScheduling(data);
        })
        .then(() => {
          this.getPage();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有排班管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportScheduling(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getPage();
    },
    // 提交导入文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style lang="scss" scoped>
.riliBox {
  // min-width: 250px;
  .item {
    background-color: #f0f0f0;
    padding:4px 10px;
    border-radius: 2px;
    margin: 4px;
    .two{
      text-wrap: nowrap;
      overflow: hidden;
    }
  }
  .item1:hover{
    background: red;
    
  }
}

.el-calendar-day {
  height: auto !important;
}
</style>
